<?php
/**
 * View common package
 *
 * @author $AUTHOR$
 * @since $DATE
 * @version $ID$
 */
defined('ANTFW_ROOT') || die('Access denied');

class antView {

    public static $data = NULL;

    public static function assign($key, $value) {
        self::$data[$key] = $value;
    }

    public static function display($template = NULL) {
        halt(200, $this->fetch($template));
    }

    public static function fetch($template) {
        // template {controller_name/template_name}
        if (FALSE === strpos($template, '/'))
            $template = CONTROLLER. '/'. $template;

        $template = APP_ROOT. 'templates/'. $template. '.php';

        file_exists($template) && is_readable($template) || halt(500, __METHOD__.'('.__LINE__.')');

        ob_start();

        extract(self::$data);
        self::$data = NULL;

        require $template;
        $content = ob_get_contents();

        ob_end_clean();

        return self::stripWhitespace($content);
    }


    /**
     * strip white space
     *
     * @param string $content
     * @return string
     */
    public static function stripWhitespace($content) {
        $stripStr = '';
        $tokens = token_get_all($content);
        $last_space = false;
        for ($i = 0, $j = count($tokens); $i < $j; $i++) {
            if (is_string($tokens[$i])) {
                $last_space = false;
                $stripStr .= $tokens[$i];
            } else {
                switch ($tokens[$i][0]) {
                case T_COMMENT:
                case T_DOC_COMMENT:
                    break;
                case T_WHITESPACE:
                    if (!$last_space) {
                        $stripStr .= ' ';
                        $last_space = true;
                    }
                    break;
                default:
                    $last_space = false;
                    $stripStr .= $tokens[$i][1];
                }
            }
        }

        return $stripStr;
    }
}
